#include "func_uart.h"
#include "string.h"
#include "usb_com.h"


extern UART_HandleTypeDef huart1;

extern unsigned char uartRec[BUFF_SIZE];
extern DMA_HandleTypeDef hdma_usart1_rx;

void uart_set_param(unsigned char *data)
{
    unsigned long baud = 0;
    HAL_UART_DeInit(&huart1);

    baud = (data[5] << 24) + (data[6] << 16) + (data[7] << 8) + (data[8]);

    huart1.Instance = USART1;
    huart1.Init.BaudRate = baud;
    switch (data[9])
    {
        case 0:
            huart1.Init.Parity = UART_PARITY_NONE;
            break;
        case 1:
            huart1.Init.Parity = UART_PARITY_ODD;
            break;
        case 2:
            huart1.Init.Parity = UART_PARITY_EVEN;
            break;

        default:
            break;
    }
    switch (data[10])
    {
        case 0:
            huart1.Init.StopBits = UART_STOPBITS_1;
            break;
        case 1:
            huart1.Init.StopBits = UART_STOPBITS_2;
            break;

        default:
            break;
    }

    switch (data[11])
    {
        case 0:
            huart1.Init.WordLength = UART_WORDLENGTH_8B;
            break;
        case 1:
            huart1.Init.WordLength = UART_WORDLENGTH_9B;
            break;

        default:
            break;
    }

    huart1.Init.Mode = UART_MODE_TX_RX;
    huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    huart1.Init.OverSampling = UART_OVERSAMPLING_16;
    if (HAL_UART_Init(&huart1) != HAL_OK)
    {
        usb_reply_ok(COMM_UART, COMM_SUB_UART_SET_PARAM, COM_FAIL);
    }
    else
    {
        usb_reply_ok(COMM_UART, COMM_SUB_UART_SET_PARAM, COM_OK);
    }
}


void uart_send_data(unsigned char *data)
{
    if (HAL_UART_Transmit_IT(&huart1, &data[5], data[2] - 6) == HAL_OK)
    {
        usb_reply_ok(COMM_UART, COMM_SUB_UART_SET_PARAM, COM_OK);
        return;
    }
    usb_reply_ok(COMM_UART, COMM_SUB_UART_SET_PARAM, COM_FAIL);
}

void uart_rec_data(unsigned char *data, unsigned long len)
{
    unsigned char sendData[64] = {0};
    sendData[0] = 0x55;
    sendData[1] = 0xaa;
    sendData[2] = len + 6;
    sendData[3] = COMM_UART;
    sendData[4] = COMM_SUB_UART_REC;
    memcpy(&sendData[5], data, len);
    sendData[len + 5] = chksum(sendData, len + 6);
    usb_send(sendData, len + 6);
}

